import { NextResponse } from "next/server"
import type { NextRequest } from 'next/server'
import {itemZodFormData,z} from "@/shared/formDataSchema"
import {createItem} from "@/server/database/repositories/itemOperation"
import { getServerUser } from "@/lib/session"
export async function POST(req: NextRequest) {
  try{
    const body = await req.json()
    itemZodFormData.parse(body)
    const user = await getServerUser() as User
    const {id: user_id} = user
    const res = await createItem({...body, user_id})
    return NextResponse.json(res)
  } catch (error) {
    if (error instanceof z.ZodError) {
      const statusMessage = error.issues.map(issue => issue.message).join("; ");
      return NextResponse.json( statusMessage, { status: 400} )
    }
    return NextResponse.json( '服务器出错，创建账目失败！', { status: 500} )
  }
}